import { App } from '@vue/runtime-dom'
import { createApp } from 'vue'

import windowAlert from './Alert.vue'

const plugin = { instance: null }

const showBox = function (content = '', title = '提示', cancel = 0, button1 = {}, button2 = {}, button3 = {}, colorTop: string) {
  if (!plugin.instance) { return }

  plugin.instance.title.value = String(title)
  plugin.instance.content.value = String(content)

  plugin.instance.button1.value = button1
  plugin.instance.button2.value = button2
  plugin.instance.button3.value = button3
  plugin.instance.cancel.value = cancel

  plugin.instance.colorTop.value = colorTop

  return new Promise(function (resolve) {
    plugin.instance.waiter.value = resolve
    plugin.instance.show.value = true
  })
}

export const $alert = function (content: string | undefined, title = '提示',
  cancel = 1,
  button1 = { text: '确定', value: true },
  button2: {} | undefined,
  button3: {} | undefined,
  colorTop: string
) {
  return showBox(content, title, cancel, button1, button2, button3, colorTop)
}

export const install = async function (app: App) {
  const appAlert = createApp(windowAlert)
  appAlert.provide('$plugin', plugin);

  (await import('../Brop')).install(appAlert)

  const domAlert = document.createElement('div')
  document.body.appendChild(domAlert)
  appAlert.mount(domAlert)

  app.provide('$alert', $alert)
}
